package main.java.LeetCode.ClassicalAlgorithm.Queue.Impl;

import main.java.LeetCode.ClassicalAlgorithm.Queue.RingBuffer;

/*
 * @author: coderOne
 * @date: 2024-09-11
 * @version: 1.0
 */

@SuppressWarnings("ALL")
public class ArrayRingBuffer<T> implements RingBuffer<T> {

    /** 写指针 */
    private volatile int write;

    /** 读指针 */
    private volatile int read;

    private final int capacity;

    /** 元素集合 */
    private final Object[] elements;

    public ArrayRingBuffer(int capacity) {
        write = 0;
        read = 0;
        this.capacity = capacity;
        elements = new Object[capacity];
    }

    @Override
    public boolean offer(T e) {

        int nextWrite = (write + 1) % capacity;

        /** 队列为满的条件是下一个写指针等于读指针，事实上下一个写指针等于读指针时，读指针的位置已经读取了，为了方便，写指针永远有一个位置不可写 */
        while (nextWrite == read) {}

        elements[nextWrite] = e;

        write = nextWrite;

        return true;
    }

    @Override
    public T take() {

        int nextRead = (read + 1) % capacity;

        /** 队列为空的条件是读指针等于写指针 */
        while (read == write) {}

        T e = (T) elements[nextRead];

        read = nextRead;
        return e;
    }
}
